import re
from google.appengine.ext import db
from django import template

from gaev.actions.url import get_action_url
import gaev
import settings

register = template.Library()


@register.filter
def attr(value, name):
	try:
		if hasattr(value, name):
			return getattr(value, name)
		elif name in value:
			return value[name]
		else:
			return '#INVALID ATTRIBUTE:%s#' % name
	except:
		if settings.DEBUG:
			return '#ERROR WHILE GETTING ATTRIBUTE %s#' % name
		else:
			return ''
		
@register.filter
def action(object, name):
	if isinstance(object, db.Key):
		object=gaev.BaseModel.get(object)
	return get_action_url(name, object)

@register.filter
@template.defaultfilters.stringfilter
def truncate(value,maxsize,stopper = '...'):
	""" truncates a string to a given maximum
		size and appends the stopper if needed """
	if value.find('<') != -1:
		return value
	from gaev.utils import human_trunc
	return human_trunc(value, maxsize, stopper)
